package com.demo.auth.common.service;

import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsRequest;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.profile.DefaultProfile;
import com.demo.auth.common.constants.PhoneConstants;
import com.demo.common.core.exception.ServiceException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @author MyPC
 */
@Component
public class SmsService {

    @Autowired
    private PhoneConstants phoneConstants;

    /**
     * 发送短信
     *
     * @param phoneNumbers 手机号
     * @param code         参数
     */
    public void sendMessage(String phoneNumbers, String code) {
        DefaultProfile profile = DefaultProfile.getProfile("cn-hangzhou", phoneConstants.getAccessId(), phoneConstants.getAccessSecret());
        IAcsClient client = new DefaultAcsClient(profile);

        SendSmsRequest request = new SendSmsRequest();
        request.setSysRegionId("cn-hangzhou");
        request.setPhoneNumbers(phoneNumbers);
        request.setSignName(phoneConstants.getSingName());
        request.setTemplateCode(phoneConstants.getTemplateCode());
        request.setTemplateParam("{\"code\":\"" + code + "\"}");
        try {
            SendSmsResponse response = client.getAcsResponse(request);
        } catch (ClientException e) {
            throw new ServiceException("短信发送失败");
        }
    }
}
